<template>
  <div class="form-wrap">
    <n-form ref="formRef" label-placement="left" size="large" :model="formData" :rules="rules">
      <n-form-item path="username">
        <n-input
          v-model:value="formData.username"
          placeholder="请输入用户名"
          @keydown.enter="handleSubmit"
          @focus="isEditUserName = true"
          @blur="userNameBlur"
        >
          <template #prefix>
            <img class="login-form-icon" src="@/assets/icons/login/username.png" alt="用户名" />
          </template>
          <template #suffix v-if="rememberUserDataLength > 0">
            <n-icon size="22" color="#000">
              <ChevronDownOutline />
            </n-icon>
          </template>
        </n-input>
        <div class="remember-user-data-wrap" v-if="isEditUserName && rememberUserDataLength > 0">
          <div
            class="user-item"
            v-for="item in rememberUserData"
            :key="item.username"
            @click="rememberUserItemTap(item)"
          >
            <avatar class="avatar" :size="42" :src="item.avatar" />
            <div class="desc">
              <div class="name">{{ item.username }}</div>
              <div class="phone">{{ item.phone }}</div>
            </div>
            <n-icon
              size="18"
              color="#9BA2AA"
              @click.stop="removeRememberUserTap(item)"
              style="cursor: pointer"
            >
              <CloseCircleSharp />
            </n-icon>
          </div>
        </div>
      </n-form-item>
      <n-form-item path="password">
        <n-input
          v-model:value="formData.password"
          type="password"
          placeholder="请输入密码"
          @keydown.enter="handleSubmit"
        >
          <template #prefix>
            <img class="login-form-icon" src="@/assets/icons/login/password.png" alt="密码" />
          </template>
        </n-input>
      </n-form-item>
      <n-form-item path="captcha">
        <n-input
          v-model:value="formData.captcha"
          placeholder="请输入验证码"
          @keydown.enter="handleSubmit"
        >
          <template #prefix>
            <n-icon size="20" color="#b4bbc2">
              <SafetyCertificateFilled />
            </n-icon>
          </template>
          <template #suffix>
            <img v-if="captchaImage" :src="captchaImage" @click="getCodeImage" style="height: 32px; width: 90px;cursor: pointer;" />
          </template>
        </n-input>
      </n-form-item>
      <div class="check-line" style="margin-bottom: 24px">
        <n-checkbox v-model:checked="isRememberPassword">记住密码</n-checkbox>
      </div>
      <n-form-item>
        <n-button
          type="primary"
          @click="handleSubmit"
          size="large"
          :loading="loading"
          block
          class="sign-btn"
        >
          登&nbsp;录
        </n-button>
      </n-form-item>
    </n-form>
  </div>
</template>

<script setup lang="ts">
  import { reactive, ref, computed } from 'vue';
  import { ChevronDownOutline, CloseCircleSharp } from '@vicons/ionicons5';
  import { SafetyCertificateFilled } from '@vicons/antd';
  import { getUserOrg, getCaptchaImage, loginParams } from '@/api/base';
  import { storage } from '@/utils/Storage';
  import crypto from '@/utils/crypto';
  import { websiteConfig } from '@/config/website.config';
  import { useRoute, useRouter } from 'vue-router';
  import { useUserStore } from '@/store/modules/user';

  const formData = reactive<loginParams>({
    username: '18875829505',
    password: '829505',
    // username: '17816827218',
    // password: '827218',
    clientType: 'SCREEN',
    timeStamp: 0,
    captcha: '',
    key: '',
  });
  const rules = {
    username: { required: true, message: '请输入用户名', trigger: 'blur' },
    password: { required: true, message: '请输入密码', trigger: 'blur' },
    captcha: { required: true, message: '请输入验证码', trigger: 'blur' },
  };

  // 记住密码
  const isRememberPassword = ref<boolean>(storage.get('isRememberPassword') || false);
  const rememberUserData = reactive(storage.get('rememberUserData') || {});
  const rememberUserDataLength = computed(() => {
    let num = 0;
    for (const key in rememberUserData) {
      if (rememberUserData[key].username !== '') {
        num++;
      }
    }
    return num;
  });
  function removeRememberUserTap(item) {
    delete rememberUserData[item.phone];
    storage.set('rememberUserData', rememberUserData);
  }
  function rememberUserItemTap(item) {
    formData.username = item.phone;
    formData.password = crypto.decrypt(item.password);
  }
  // 是否在输入用户名
  const isEditUserName = ref(false);
  function userNameBlur() {
    setTimeout(() => {
      isEditUserName.value = false;
    }, 300);
  }
  const userStore = useUserStore();
  const router = useRouter();
  const route = useRoute();
  const formRef = ref();
  const loading = ref(false);
  const captchaImage = ref('');
  function getCodeImage() {
    getCaptchaImage().then((res) => {
      captchaImage.value = res.image;
      formData.key = res.key;
    });
  }
  getCodeImage();
  const handleSubmit = (e) => {
    e.preventDefault();
    formRef.value.validate(async (errors) => {
      if (!errors) {
        window['$message'].loading('登录中...');
        loading.value = true;
        try {
          const timeStamp = Date.now();
          const orgData = await getUserOrg(
            crypto.encrypt(
              JSON.stringify({
                timeStamp: timeStamp,
                username: formData.username,
                clientType: formData.clientType,
              })
            )
          );
          const userInfo = await userStore.login(
            crypto.encrypt(
              JSON.stringify({
                timeStamp: timeStamp,
                username: formData.username,
                clientType: formData.clientType,
                password: formData.password,
                orgId: orgData[0].id,
                captcha: formData.captcha,
                key: formData.key,
              })
            )
          );
          window['$message'].destroyAll();
          window['$message'].success('登录成功，即将进入' + websiteConfig.title);
          storage.set('isRememberPassword', isRememberPassword.value);
          if (isRememberPassword.value) {
            rememberUserData[formData.username] = {
              username: userInfo.username,
              phone: userInfo.phone,
              password: crypto.encrypt(formData.password),
              avatar: userInfo.pic,
            };
            storage.set('rememberUserData', rememberUserData);
          }
          await router.replace('/home/index');
        } catch (e) {
          console.log(e)
          getCodeImage();
        } finally {
          loading.value = false;
        }
      } else {
        window['$message'].error('请填写完整信息，并且进行验证码校验');
      }
    });
  };
</script>

<style scoped lang="less">
  .form-wrap {
    ::v-deep(.n-input__border) {
      border-radius: 8px;
    }
    ::v-deep(.n-input__state-border) {
      border-radius: 8px;
    }
    ::v-deep(.n-button) {
      border-radius: 8px;
    }
  }
  .login-form-icon {
    width: 20px;
    height: 20px;
  }
  .remember-user-data-wrap {
    position: absolute;
    top: 48px;
    left: 0;
    right: 0;
    max-height: 300px;
    border-radius: 9px;
    background-color: #fff;
    box-shadow: 0 3px 6px -4px rgba(0, 0, 0, 0.12), 0 6px 16px 0 rgba(0, 0, 0, 0.08),
      0 9px 28px 8px rgba(0, 0, 0, 0.05);
    z-index: 2;
    padding: 0 16px;
    .user-item {
      display: flex;
      align-items: center;
      padding: 10px 0;
      border-bottom: 1px solid #e6eaed;
      cursor: pointer;
      &:last-child {
        border-bottom: 0;
      }
      .desc {
        margin: 0 8px;
        flex: 1;
      }
      .name {
        font-size: 16px;
      }
      .phone {
        font-size: 14px;
        color: #9ba2aa;
      }
    }
  }
</style>
